use std::{env,collections::HashMap};
use oracle::{Connection, Result, Version};
use log::{info,debug};
use log4rs;

fn main() -> Result<()> {
    log4rs::init_file("log.yaml", Default::default()).unwrap();

    let svc = match env::var_os("SVC_NAME") {
        Some(v) => v.into_string().unwrap(),
        None => panic!("$SVC_NAME is not set")
    };
    let username = match env::var_os("USERNAME") {
        Some(v) => v.into_string().unwrap(),
        None => panic!("$SVC_NAME is not set")
    };
    let password = match env::var_os("PASSWORD") {
        Some(v) => v.into_string().unwrap(),
        None => panic!("$SVC_NAME is not set")
    };
    debug!("\nService Name is {}", svc);

    let args: Vec<String> = env::args().collect();

    let client_ver = Version::client()?;
    debug!("\nOracle Client Version: {}", client_ver);

    let conn = Connection::connect(username, password, svc)?;
    let (server_ver, banner) = conn.server_version()?;

    debug!("\nDatabase Server Version: {}", server_ver);
    debug!("\nServer Banner: {}\n", banner);

    //let sql = "select * from v$instance";
    let mut stmt = conn.statement(&args[1]).build()?;
    let rows = stmt.query(&[])?;

    // Get the column names
    let mut column_vec = vec![];
    for info in rows.column_info() {
        column_vec.push(info.name().to_string());
        //print!("{} ", info.name())
    }

    // Display the resultset
    for row_result in rows {
        // print column values
        let mut map = HashMap::new();
        for (idx, val) in row_result?.sql_values().iter().enumerate() {
            /*
            if idx != 0 {
                print!(",");
            }
            print!("{}", val);
            */
            map.insert(column_vec.get(idx), format!("{}",val));
        }
        //println!();
        info!("\n{}", serde_json::to_string(&map).unwrap());
    }
    conn.close()?;

    Ok(())
}